package com.yzt.message.widget.chatinput.widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;


import com.yzt.message.widget.chatinput.emoji.data.EmojiBean;
import com.yzt.zhuju.widget.emticonnskeyboard.CustomEmojiFilter;
import com.yzt.zhuju.widget.emticonnskeyboard.EmoticonsEditText;
import com.yzt.zhuju.widget.emticonnskeyboard.data.EmoticonEntity;
import com.yzt.zhuju.widget.emticonnskeyboard.interfaces.EmoticonClickListener;
import com.yzt.zhuju.widget.emticonnskeyboard.utils.EmoticonsKeyboardUtils;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.plugin_widget.voicerecordview.RecordControllerView;
import com.yzt.plugin_widget.voicerecordview.RecordVoiceActionListener;
import com.yzt.plugin_widget.voicerecordview.RecordVoiceButton;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;

import com.yzt.message.R;
import com.yzt.message.widget.chatinput.ChatInputStyle;
import com.yzt.message.widget.chatinput.listener.OnFileSelectedListener;
import com.yzt.message.widget.chatinput.listener.RecordVoiceListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.yzt.message.widget.chatinput.listener.OnMenuClickListener;
import com.yzt.message.widget.chatinput.listener.OnMenuStatusChangedListener;
import com.yzt.message.widget.chatinput.model.FileItem;
import com.yzt.message.widget.chatinput.model.VideoItem;
import com.yzt.message.widget.chatinput.photo.SelectPhotoView;
import com.yzt.message.widget.chatinput.utils.SimpleCommonUtils;

@SuppressLint("SetTextI18n")
public class ChatInputView extends LinearLayout implements View.OnClickListener, TextWatcher, RecordControllerView.OnRecordActionListener, OnFileSelectedListener, ViewTreeObserver.OnGlobalLayoutListener {

    public final static int VOICE_TIME_LENGTH = 61;

    private CharSequence mInput;

    /**
     * 底部的按钮
     */
    private EmoticonsEditText mChatInput;
    private TextView mSendBtn;
    private ImageButton mVoiceBtn;
    private ImageButton mEmojiBtn;
    private ImageButton mMoreBtn;

    private LinearLayout mChatMoreContainer;
    private RelativeLayout mChatInputContainer;
    private FrameLayout mMenuItemContainer;
    private FrameLayout mMenuContainer;
    private RelativeLayout mRecordVoiceRl;
    private LinearLayout mRecordContentLl;

    private TextView mAuroraShowTimeTv;
    private TextView mRecordTv;
    private TextView mRecordHintTv;
    private ImageView mLeftDefaultIv;
    private ImageView mRightDefaultIv;
    private SVGAImageView mLeftDefaultSvga;
    private SVGAImageView mRightDefaultSvga;

    private RecordVoiceButton mRecordVoiceBtn;
    private SelectPhotoView mSelectPhotoView;
    private ImageButton mSelectAlbumIb;
    private ImageButton mSelectCameraIb;

    private OnMenuClickListener mListener;
    private OnMenuStatusChangedListener menuStatusChangedListener;

    private ChatInputStyle mStyle;

    private InputMethodManager mImm;
    private Window mWindow;
    private FragmentActivity mActivity;

    private LinearLayout llEmoji;

    private int mHeight;
    private int mSoftKeyboardHeight;
    private int mOldh;
    public static int sMenuHeight = DisplayUtils.dp2px(280);

    private boolean mShowSoftInput = false;

    private MediaPlayer mMediaPlayer = new MediaPlayer();

    // To judge if is finish recording video
    private boolean mFinishRecordingVideo = false;

    // Video file to be saved at
    private String mVideoFilePath;

    private boolean mIsFullScreen = false;
    private Context mContext;
    private boolean mInit = true;

    private boolean isRyIm;

    public ChatInputView(Context context) {
        super(context);
        init(context);
    }

    public ChatInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ChatInputView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @SuppressLint({"WrongViewCast", "ClickableViewAccessibility"})
    private void init(Context context) {
        mContext = context;
        inflate(context, R.layout.view_chatinput, this);

        // menu buttons
        mChatInput = findViewById(R.id.aurora_et_chat_input_1);
        mChatInput.addEmoticonFilter(new CustomEmojiFilter());

        mSendBtn = findViewById(R.id.aurora_menuitem_ib_send);
        mSendBtn.setOnClickListener(onMenuItemClickListener);

        mVoiceBtn = findViewById(R.id.aurora_menu_item_ib_voice);
        mEmojiBtn = findViewById(R.id.aurora_menu_item_ib_emoji);
        mMoreBtn = findViewById(R.id.aurora_menu_item_ib_plus);

        findViewById(R.id.aurora_fl_menu_item_voice).setOnClickListener(onMenuItemClickListener);
        findViewById(R.id.tv_chat_page_more_touzi).setOnClickListener(onMenuItemClickListener);
        findViewById(R.id.aurora_fl_menu_item_emoji).setOnClickListener(onMenuItemClickListener);
        findViewById(R.id.aurora_fl_menu_item_gift).setOnClickListener(onMenuItemClickListener);
        findViewById(R.id.aurora_fl_menu_item_red_package).setOnClickListener(onMenuItemClickListener);
        findViewById(R.id.aurora_fl_menu_item_photo).setOnClickListener(onMenuItemClickListener);
        findViewById(R.id.aurora_fl_menu_item_plus).setOnClickListener(onMenuItemClickListener);

        findViewById(R.id.tv_edit_sure).setOnClickListener(onMenuItemClickListener);
        findViewById(R.id.iv_edit_del).setOnClickListener(onMenuItemClickListener);

        mChatMoreContainer = findViewById(R.id.chat_more_panel);
        mChatInputContainer = findViewById(R.id.aurora_ll_input_container);
        mMenuItemContainer = findViewById(R.id.aurora_ll_menuitem_container);
        mMenuContainer = findViewById(R.id.aurora_fl_menu_container);
        mRecordVoiceRl = findViewById(R.id.aurora_rl_recordvoice_container);
        mRecordContentLl = findViewById(R.id.aurora_ll_recordvoice_content_container);

        RecordControllerView mRecordControllerView = findViewById(R.id.aurora_rcv_recordvoice_controller);
        mAuroraShowTimeTv = findViewById(R.id.aurora_show_time_tv);
        mRecordTv = findViewById(R.id.aurora_tv_recordvoice);
        mRecordHintTv = findViewById(R.id.aurora_tv_recordvoice_hint);

        mLeftDefaultIv = findViewById(R.id.left_default_iv);
        mRightDefaultIv = findViewById(R.id.right_default_iv);
        mLeftDefaultSvga = findViewById(R.id.left_default_svga);
        mRightDefaultSvga = findViewById(R.id.right_default_svga);

        mRecordVoiceBtn = findViewById(R.id.aurora_rvb_recordvoice_record);

        mSelectPhotoView = findViewById(R.id.aurora_view_select_photo);
        mSelectAlbumIb = findViewById(R.id.aurora_imagebtn_selectphoto_album);
        mSelectCameraIb = findViewById(R.id.aurora_imagebtn_selectphoto_camera);
        mSelectPhotoView.initData();
        llEmoji = findViewById(R.id.ll_emoji);

        mMenuContainer.setVisibility(GONE);

        mChatInput.addTextChangedListener(this);

        mRecordVoiceBtn.setRecordController(mRecordControllerView);
        mRecordVoiceBtn.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mListener.openRecordPermission();
                }
                return false;
            }
        });

        mImm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        mWindow = ((Activity) context).getWindow();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int mWidth = dm.widthPixels;
        mHeight = dm.heightPixels;
        mRecordControllerView.setWidth(mWidth);
        mRecordControllerView.setOnControllerListener(this);
        getViewTreeObserver().addOnGlobalLayoutListener(this);

        mChatInput.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (mInit && mSoftKeyboardHeight != 0) {
                    setMenuContainerHeight(getSoftKeyboardHeight());
                    mInit = false;
                }
                if (!mChatInput.isFocused()) {
                    mChatInput.setFocusable(true);
                    mChatInput.setFocusableInTouchMode(true);
                }
                dismissMenuLayout();
                mShowSoftInput = true;
                return false;
            }
        });
    }

    EmoticonClickListener emoticonClickListener = new EmoticonClickListener() {
        @Override
        public void onEmoticonClick(Object o, int actionType, boolean isDelBtn) {
            if (isDelBtn) {
                SimpleCommonUtils.delClick(mChatInput);
            } else {
                if (o == null) {
                    return;
                }
                String content = null;
                if (o instanceof EmojiBean) {
                    content = ((EmojiBean) o).emoji;
                } else if (o instanceof EmoticonEntity) {
                    content = ((EmoticonEntity) o).getContent();
                }

                if (TextUtils.isEmpty(content)) {
                    return;
                }
                int index = mChatInput.getSelectionStart();
                Editable editable = mChatInput.getText();
                editable.insert(index, content);
            }
        }
    };

    public void setRyIm(boolean isRyIm) {
        this.isRyIm = isRyIm;
    }

    private void init(Context context, AttributeSet attrs) {
        init(context);
        setMenuContainerHeight(getSoftKeyboardHeight());
        mStyle = ChatInputStyle.parse(context, attrs);

        mChatInput.setMaxLines(mStyle.getInputMaxLines());
        mChatInput.setHint(mStyle.getInputHint());
        mChatInput.setText(mStyle.getInputText());
        mChatInput.setTextSize(TypedValue.COMPLEX_UNIT_PX, mStyle.getInputTextSize());
        mChatInput.setTextColor(mStyle.getInputTextColor());
        mChatInput.setHintTextColor(mStyle.getInputHintColor());
        mChatInput.setBackgroundResource(mStyle.getInputEditTextBg());
        mChatInput.setPadding(mStyle.getInputPaddingLeft(), mStyle.getInputPaddingTop(), mStyle.getInputPaddingRight() + DisplayUtils.getDimensionPixelSize(R.dimen.dp_34), mStyle.getInputPaddingBottom());
        mSelectAlbumIb.setVisibility(mStyle.getShowSelectAlbum() ? VISIBLE : INVISIBLE);
        mSelectCameraIb.setVisibility(mStyle.getShowSelectAlbum() ? VISIBLE : INVISIBLE);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
        SimpleCommonUtils.initEmoticonsEditText(mChatInput);
    }

    public void setMenuClickListener(OnMenuClickListener listener) {
        mListener = listener;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mInput = s;
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    public EditText getInputView() {
        return mChatInput;
    }

    private int mShowMenuId;

    private final OnClickListener onMenuItemClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.aurora_menuitem_ib_send) {
                sendTextMsg();
            } else if (view.getId() == R.id.iv_edit_del) {
                mChatInput.deleteChar();
            } else if (view.getId() == R.id.tv_edit_sure) {
                dismissMenuLayout();
            } else if (view.getId() == R.id.aurora_fl_menu_item_gift) {
                if (mListener != null && mListener.switchToGiftMenu()) {
                    dismissRecordVoiceLayout();
                    dismissPhotoLayout();
                    dismissMoreLayout();
                    dismissMenuLayout();
                    dismissEmojiLayout();
                }
            } else if (view.getId() == R.id.aurora_fl_menu_item_red_package) {
                if (mListener != null && mListener.switchToRedPackageMenu()) {
                    dismissMenuLayout();
                }
            } else if (view.getId() == R.id.aurora_fl_menu_item_photo) {
                if (isRyIm) {
                    if (mListener != null) {
                        dismissRecordVoiceLayout();
                        dismissPhotoLayout();
                        dismissMoreLayout();
                        dismissGiftLayout();
                        dismissMenuLayout();
                        mListener.switchToGalleryMode();
                    }
                } else { // todo
                    if (mListener != null && mListener.switchToGalleryMode()) {
                        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        showSelectPhotoLayout();
                        mSelectPhotoView.initData();
                    }
                }
            } else {
                boolean showVoice = false;
                if (view.getId() == R.id.aurora_fl_menu_item_voice) {
                    if (mListener != null && mListener.switchToVoiceMenu()) {
                        showVoice = true;
                        showRecordVoiceLayout();
                        //setMenuContainerHeight(sMenuHeight);
                    }
                } else if (view.getId() == R.id.tv_chat_page_more_touzi) {
                    if (mListener != null && mListener.switchTouzi()) {

                    }
                } else if (view.getId() == R.id.aurora_fl_menu_item_emoji) {
                    if (mListener != null && mListener.switchToEmojiMode()) {
                        showEmojiLayout();
                    }
                } else if (view.getId() == R.id.aurora_fl_menu_item_plus) {
                    if (mListener != null && mListener.switchToMoreMenu()) {
                        showMoreLayout();
                        setMenuContainerHeight(sMenuHeight);
                    }
                } else if (mShowMenuId == view.getId()) {
                    dismissMenuLayout();
                }

                if (mMenuContainer.getVisibility() != VISIBLE) {
                    if (view.getId() == R.id.aurora_fl_menu_item_voice) {
                        if (showVoice) {
                            dismissSoftInputAndShowMenu();
                        }
                    } else {
                        dismissSoftInputAndShowMenu();
                    }
                }

                mShowMenuId = view.getId();
                if (mShowSoftInput) {
                    EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInput);
                    mShowSoftInput = false;
                }
            }
        }
    };

    public void dismissSoftInputAndShowMenu() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        showMenuLayout();
        if (mImm != null) {
            mImm.hideSoftInputFromWindow(mChatInput.getWindowToken(), 0);
        }
        mShowSoftInput = false;
    }

    /**
     * 发送文本消息
     */
    public void sendTextMsg() {
        if (onSubmit()) {
            mChatInput.setText("");
        }
        if (mSelectPhotoView.getSelectFiles() != null && mSelectPhotoView.getSelectFiles().size() > 0) {
            mListener.onSendFiles(mSelectPhotoView.getSelectFiles());
            mSelectPhotoView.resetCheckState();
            dismissMenuLayout();
            mImm.hideSoftInputFromWindow(getWindowToken(), 0);
            mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mShowSoftInput = false;
        }
    }

    @Override
    public void onClick(View view) {
        if (mFinishRecordingVideo) {
            if (mListener != null) {
                VideoItem video = new VideoItem(mVideoFilePath, null, null, 0, mMediaPlayer.getDuration());
                List<FileItem> list = new ArrayList<>();
                list.add(video);
                mListener.onSendFiles(list);
                mFinishRecordingVideo = false;
                mVideoFilePath = null;
            }
            mMediaPlayer.stop();
            mMediaPlayer.release();
            recoverScreen();
            dismissMenuAndResetSoftMode();
        }
    }

    public void setRecordVoiceFile(String path, String fileName) {
        mRecordVoiceBtn.setVoiceFilePath(path, fileName);
    }

    public void setRecordVoiceListener(RecordVoiceListener listener) {
        this.mRecordVoiceBtn.setRecordVoiceListener(new RecordVoiceActionListener() {
            @Override
            public void onStartRecord() {
                listener.onStartRecord();
            }

            @Override
            public void onFinishRecord(File voiceFile, int duration) {
                listener.onFinishRecord(voiceFile, duration);
            }

            @Override
            public void onCancelRecord() {
                listener.onCancelRecord();
            }

            @Override
            public void onPreviewCancel() {
                listener.onPreviewCancel();
            }

            @Override
            public void onPreviewSend() {
                listener.onPreviewSend();
            }
        });
    }

    /**
     * Recover screen
     */
    private void recoverScreen() {
        final Activity activity = (Activity) getContext();
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
                attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                activity.getWindow().setAttributes(attrs);
                activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                mIsFullScreen = false;
                mChatInputContainer.setVisibility(VISIBLE);
                mMenuItemContainer.setVisibility(VISIBLE);
                setMenuContainerHeight(sMenuHeight);
                ViewGroup.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, sMenuHeight);
            }
        });
    }

    public void dismissMenuLayout() {
        mMenuContainer.setVisibility(GONE);
        if (menuStatusChangedListener != null) {
            menuStatusChangedListener.onMenuStatusChanged(false);
        }
        mEmojiBtn.setImageResource(R.drawable.chat_screen_expression);
        mMoreBtn.setImageResource(R.drawable.chat_page_bottom_bt7);
        mVoiceBtn.setImageResource(R.drawable.icon_voice_input_defalut);
    }

    public void showMenuLayout() {
        mMenuContainer.setVisibility(VISIBLE);
        if (menuStatusChangedListener != null) {
            menuStatusChangedListener.onMenuStatusChanged(true);
        }
    }

    public void showGiftLayout() {
        dismissMoreLayout();
        dismissEmojiLayout();
        dismissPhotoLayout();
        dismissRecordVoiceLayout();
        setMenuContainerHeight(sMenuHeight);
    }

    public void dismissGiftLayout() {

    }

    public void showMoreLayout() {
        dismissGiftLayout();
        dismissEmojiLayout();
        dismissPhotoLayout();
        dismissRecordVoiceLayout();
        setMenuContainerHeight(sMenuHeight);
        mChatMoreContainer.setVisibility(View.VISIBLE);
        mMoreBtn.setImageResource(R.drawable.chat_menu_more_choosed);
    }

    public void dismissMoreLayout() {
        mChatMoreContainer.setVisibility(View.GONE);
        mMoreBtn.setImageResource(R.drawable.chat_page_bottom_bt7);
    }

    public void showRecordVoiceLayout() {
        mVoiceBtn.setImageResource(R.drawable.icon_voice_btn_input_ing);
        mSelectPhotoView.setVisibility(GONE);
        llEmoji.setVisibility(View.GONE);
        if (mEmojiView != null) {
            mEmojiView.closeEmoji();
        }
        dismissMoreLayout();
        mRecordVoiceRl.setVisibility(VISIBLE);
        mRecordContentLl.setVisibility(VISIBLE);
    }

    public void dismissRecordVoiceLayout() {
        mRecordVoiceRl.setVisibility(GONE);
    }

    public void showSelectPhotoLayout() {
        dismissRecordVoiceLayout();
        dismissEmojiLayout();
        dismissMoreLayout();
        dismissGiftLayout();
        mSelectPhotoView.setVisibility(VISIBLE);
        setMenuContainerHeight(DisplayUtils.dp2px(200));
    }

    public void dismissPhotoLayout() {
        mSelectPhotoView.setVisibility(View.GONE);
    }

    CustomEmojiView mEmojiView;

    public void showEmojiLayout() {
        dismissRecordVoiceLayout();
        dismissPhotoLayout();
        dismissMoreLayout();
        dismissGiftLayout();
        llEmoji.setVisibility(View.VISIBLE);
        mEmojiBtn.setImageResource(R.drawable.chat_screen_expression_click);
        if (null == mEmojiView) {
            mEmojiView = new CustomEmojiView();
            mEmojiView.setOnSelectEmojiListener(new CustomEmojiView.OnSelectEmojiListener() {
                @Override
                public void selectEmoji(String msg, String emojiPath, int gameResult, int type) {
                    String content = msg;
                    int index = mChatInput.getSelectionStart();
                    Editable editable = mChatInput.getText();
                    editable.insert(index, content);
                }
            });
            mEmojiView.bindView(mActivity, findViewById(R.id.ll_emoji));
        }
        mEmojiView.setDefaultSelect();

        setMenuContainerHeight(sMenuHeight);
    }

    public void dismissEmojiLayout() {
        llEmoji.setVisibility(View.GONE);
        if (mEmojiView != null) {
            mEmojiView.closeEmoji();
        }
        mEmojiBtn.setImageResource(R.drawable.chat_screen_expression);
    }

    /**
     * Set menu container's height, invoke this method once the menu was initialized.
     *
     * @param height Height of menu, set same height as soft keyboard so that display to perfection.
     */
    public void setMenuContainerHeight(int height) {
        if (height > 0) {
//            if (update) {
//                sMenuHeight = height;
//            }
            ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
            mMenuContainer.setLayoutParams(params);
        }
    }

    private boolean onSubmit() {
        return mListener != null && mListener.onSendTextMessage(mInput, false);
    }

    public boolean getSoftInputState() {
        return mShowSoftInput;
    }

    public void setSoftInputState(boolean state) {
        mShowSoftInput = state;
    }

    public int getMenuState() {
        return mMenuContainer.getVisibility();
    }

    public int getMoreState() {
        return mChatMoreContainer.getVisibility();
    }

    /**
     * Select photo callback
     */
    @Override
    public void onFileSelected() {
        int size = mSelectPhotoView.getSelectFiles().size();
        Log.i("ChatInputView", "select file size: " + size);
        if (mInput.length() == 0 && size == 1) {
            mSendBtn.setVisibility(VISIBLE);
        }
    }

    /**
     * Cancel select photo callback
     */
    @Override
    public void onFileDeselected() {
        int size = mSelectPhotoView.getSelectFiles().size();
        Log.i("ChatInputView", "deselect file size: " + size);
        if (mInput.length() == 0) {
            mSendBtn.setVisibility(GONE);
        }
    }

    /**
     * Record audio widget finger on touch record button callback
     */
    @Override
    public void onStart() {
        Log.e("ChatInputView", "starting chronometer");

        mRecordTv.setText(mContext.getString(R.string.release_send) + "\t 0“");
        mRecordTv.setVisibility(VISIBLE);
        mTimeCounter = new TimeCounter(VOICE_TIME_LENGTH * 1000, 1000);// 构造CountDownTimer对象，总时长60s，每1s
        mTimeCounter.start();

        mRecordHintTv.setVisibility(INVISIBLE);
        mAuroraShowTimeTv.setVisibility(GONE);
        initSvgaInit(false);
    }

    /**
     * Recording audio mode, finger moving callback
     */
    @Override
    public void onMoving() {
        mRecordTv.setVisibility(VISIBLE);
        mRecordHintTv.setVisibility(INVISIBLE);
    }

    /**
     * Recording audio mode, finger moved left button (preview button) callback
     */
    @Override
    public void onMovedLeft() {
        mRecordTv.setVisibility(INVISIBLE);
        mRecordHintTv.setVisibility(VISIBLE);
        mRecordHintTv.setText(getContext().getString(R.string.preview_play_audio_hint));
    }

    @Override
    public void onMovedTop() {
        mRecordTv.setVisibility(INVISIBLE);
        mRecordHintTv.setVisibility(VISIBLE);
        mRecordHintTv.setText(getContext().getString(R.string.cancel_record_voice_hint));
    }

    /**
     * Recording audio mode, finger moved left button and release
     */
    @Override
    public void onLeftUpTapped() {

        if (mTimeCounter != null) {
            mTimeCounter.cancel();
        }
        mRecordTv.setVisibility(INVISIBLE);

        mRecordHintTv.setVisibility(INVISIBLE);
        mRecordContentLl.setVisibility(GONE);
    }

    /**
     * Recording audio mode, finger moved right button and release
     */
    @Override
    public void onRightUpTapped() {
        if (mTimeCounter != null) {
            mTimeCounter.cancel();
        }
        mRecordTv.setVisibility(INVISIBLE);
        mRecordTv.setText(mContext.getString(R.string.release_send) + "\t 0“");
        mRecordHintTv.setText(getContext().getString(R.string.record_voice_hint));
        mRecordHintTv.setVisibility(VISIBLE);

        mAuroraShowTimeTv.setVisibility(GONE);
        initSvgaInit(false);
    }

    public void dismissMenuAndResetSoftMode() {
        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        dismissMenuLayout();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mMediaPlayer.release();
        getViewTreeObserver().removeOnGlobalLayoutListener(this);
        mMediaPlayer = null;
    }

    @Override
    public void onGlobalLayout() {
        if (mSoftKeyboardHeight == 0) {
            try {
                Rect r = new Rect();
                ((Activity) mContext).getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                int mNowh = mHeight - r.bottom;
                if (mOldh != -1 && mNowh != mOldh) {
                    mShowSoftInput = mNowh > 0;
                    if (mShowSoftInput) {
                        mSoftKeyboardHeight = mNowh;
                    }
                }
                mOldh = mNowh;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public int getSoftKeyboardHeight() {
        return this.mSoftKeyboardHeight;
    }

    public ChatInputStyle getStyle() {
        return this.mStyle;
    }

    public ImageButton getSelectAlbumBtn() {
        return this.mSelectAlbumIb;
    }

    public ImageButton getSelectCameraBtn() {
        return this.mSelectCameraIb;
    }

    public EmoticonsEditText getInputEditText() {

        return mChatInput;
    }

    public void setActivity(FragmentActivity mActivity) {
        this.mActivity = mActivity;
    }

    private TimeCounter mTimeCounter;

    public void setEditText(String content) {
        if (mChatInput != null) {
            mChatInput.setText(content);
            mChatInput.setSelection(content.length());
            EmoticonsKeyboardUtils.openSoftKeyboard(mChatInput);
            dismissMenuLayout();
        }
    }

    private class TimeCounter extends CountDownTimer {
        /**
         * @param millisInFuture    总时长
         * @param countDownInterval 计时时间间隔
         */
        public TimeCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            int time = (int) (millisUntilFinished / 1000);
            if (time < 10) {
                mAuroraShowTimeTv.setVisibility(VISIBLE);
                mAuroraShowTimeTv.setText(mContext.getString(R.string.recording_will_stop_in_seconds) + time);
            } else {
                mAuroraShowTimeTv.setVisibility(GONE);
            }
            mRecordTv.setText(mContext.getString(R.string.release_send) + "\t" + (VOICE_TIME_LENGTH - time - 1) + "“");
            initSvgaInit(true);
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            mAuroraShowTimeTv.setVisibility(GONE);
            mRecordVoiceBtn.finishRecord(true);
            mRecordTv.setText(mContext.getString(R.string.release_send) + "\t 60“");
            initSvgaInit(false);
        }

    }

    public void initSvgaInit(boolean anim) {
        if (anim) {
            mLeftDefaultIv.setVisibility(GONE);
            mRightDefaultIv.setVisibility(GONE);
            mLeftDefaultSvga.setVisibility(VISIBLE);
            mRightDefaultSvga.setVisibility(VISIBLE);

            new SVGAParser(mActivity).decodeFromAssets("chat_voice_left.svga", new SVGAParser.ParseCompletion() {

                @Override
                public void onComplete(SVGAVideoEntity videoItem) {
                    if (mLeftDefaultSvga != null) {
                        mLeftDefaultSvga.setVideoItem(videoItem);
                        mLeftDefaultSvga.stepToFrame(0, true);
                    }
                }

                @Override
                public void onError() {

                }
            }, null);
            new SVGAParser(mActivity).decodeFromAssets("chat_voice_right.svga", new SVGAParser.ParseCompletion() {

                @Override
                public void onComplete(SVGAVideoEntity videoItem) {
                    if (mRightDefaultSvga != null) {
                        mRightDefaultSvga.setVideoItem(videoItem);
                        mRightDefaultSvga.stepToFrame(0, true);
                    }
                }

                @Override
                public void onError() {

                }
            }, null);
        } else {
            mLeftDefaultIv.setVisibility(VISIBLE);
            mRightDefaultIv.setVisibility(VISIBLE);
            mLeftDefaultSvga.setVisibility(GONE);
            mRightDefaultSvga.setVisibility(GONE);
        }
    }

    /**
     * 群聊隐藏礼物和红包
     */
    public void setGroupChat(String targetId) {
        if (targetId.length() > 15) {
          //  findViewById(R.id.rl_base_redpack_container).setVisibility(View.INVISIBLE);
            findViewById(R.id.ll_base_gift_container).setVisibility(View.INVISIBLE);
        }
    }
}